<template>
	<div class="knowledge-base-container">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="知识库管理" name="knowledge">
				<GroupList
					:groupList="groupList"
					:queryMode="queryMode"
					ref="groupList"
					@create="handleCreateGroup"
					@select="handleGroupSelect"
					@modify="handleGroupEdit"
					@remove="handleGroupRemove"
					@add="handleGroupAdd"
				/>
				<QuestionList :group="curGroup" :groupList="groupList" :queryMode="queryMode" ref="QuestionList" @edit-catagory="handleEditCatagory" @search="handleSearch" @created="handleCreateQuestion"/>
			</el-tab-pane>
		</el-tabs>
		<CreateGroup
			v-if="createGroupVisible"
			:visible="createGroupVisible"
			:group="curGroup"
			:parentId="parentGroupId"
			@close="createGroupVisible = false"
			@confirm="handleCreateGroupConfirm"
			@edit-name="handleGroupNameEdit"
		></CreateGroup>
		<EditGroup v-if="editGroupVisible" :visible="editGroupVisible" :group="curGroup" :groupList="groupList" @close="editGroupVisible = false" @confirm="handleEditCatagoryConfirm"></EditGroup>
	</div>
</template>
<script>
// import { groupMock } from './mock';
import CreateGroup from './CreateGroup.vue';
import GroupList from './GroupList.vue';
import QuestionList from './QuestionList.vue';
import { getKnowledgeBaseCategoryAll, updateKnowledgeBaseCategory, deleteKnowledgeBaseCategory, batchUpdateKnowledgeBaseCategory, getKnowledgeBaseCategoryParent } from '@/api/api';
import EditGroup from './EditGroup.vue';
import { extractIds } from '@/utils/MyVueUtil.js';
const DefaultCategory = [
	{
		id: 'all',
		name: '全部问题',
		default: true
	},
	{
		id: 0,
		name: '未分类',
		default: true
	}
];
export default {
	components: {
		CreateGroup,
		GroupList,
		QuestionList,
		EditGroup
	},
	data() {
		return {
			activeName: 'knowledge',
			groupList: [],
			createGroupVisible: false,
			curGroup: {},
			editGroupVisible: false,
			parentGroupId: 0,
			curMultipleSelection: [],
			queryMode: 'category', // 查询模式 category | search
			curSearchName: '' // 当前搜索项
		};
	},
	mounted() {
		this.getKnowledgeBaseCategoryList();
	},
	methods: {
		// 新增分类
		handleCreateGroup() {
			this.curGroup = {};
			this.parentGroupId = 0;
			this.createGroupVisible = true;
		},
		// 新增分类窗口关闭
		handleCreateGroupConfirm(data) {
			const { level, parentId } = data;
			// 获取分类列表
			this.createGroupVisible = false;
			// append data to groupList
			if (parentId === 0) {
				this.groupList.push({...data});
			} else {
				if (level === '2') {
					for (let i = 0; i < this.groupList.length; i++) {
						const item = this.groupList[i];
						if (item.id === parentId) {
							if (item.children) {
								item.children.push({...data});
							} else {
								this.$set(item, 'children', [data]);
							}
							break;
						}
					}
				} else {
					this.groupList.forEach(item => {
						if (item.children) {
							item.children.forEach(subItem => {
								if (subItem.id === parentId) {
									console.log('level 2', subItem);
									if (subItem.children) {
										subItem.children.push({...data});
									} else {
										this.$set(subItem, 'children', [data]);
									}
								}
							});
						}
					});
				}
				// 展开父节点
				this.$nextTick(() => {
					this.$refs.groupList.addExpandedKeys(parentId);
				});
			}
			this.queryMode = 'category';
			// 展开父节点
			this.$nextTick(() => {
				this.$refs.groupList.setCurrentKey(data.id);
				this.curGroup = {...data};
			});
		},
		// 编辑分类名称
		handleGroupNameEdit(data) {
			this.createGroupVisible = false;
			console.log('handleGroupNameEdit', data);
			const { level, parentId } = data;
			if (level === '1') {
				const index = this.groupList.findIndex(item => item.id === data.id);
				this.groupList[index].name = data.name;
			} else if (level === '2') {
				for (let i = 0; i < this.groupList.length; i++) {
					const item = this.groupList[i];
					if (item.id === parentId && item.children) {
						const index = item.children.findIndex(item => item.id === data.id);
						item.children[index].name = data.name;
						break;
					}
				}
			} else {
				this.groupList.forEach(item => {
					if (item.children) {
						item.children.forEach(subItem => {
							if (subItem.id === parentId && subItem.children) {
								const index = subItem.children.findIndex(item => item.id === data.id);
								subItem.children[index].name = data.name;
							}
						});
					}
				});
			}
		},
		// 选择分类
		handleGroupSelect(data) {
			console.log('handleGroupSelect', data);
			this.$refs.QuestionList.clearSearchName();
			this.queryMode = 'category';
			this.curGroup = data;
		},
		// 获取分类列表s
		getKnowledgeBaseCategoryList() {
			getKnowledgeBaseCategoryAll()
				.then(res => {
					console.log(res);
					const { data } = res.data;
					this.groupList = data;
					this.groupList.unshift(...DefaultCategory);
					if (this.groupList[0]) {
						if (this.curGroup.id === this.groupList[0].id) {
							this.$refs.QuestionList.getKnowledgeBaseList();
						} else {
							this.curGroup = this.groupList[0];
						}
					}
				})
				.catch(err => {
					console.log(err);
				});
		},
		// 处理分类编辑
		handleGroupEdit(data) {
			console.log(data);
			this.curGroup = data;
			this.createGroupVisible = true;
		},
		// 删除分类
		deleteKnowledgeBaseCategory(data) {
			const { level, parentId } = data;
			console.log('deleteKnowledgeBaseCategory ', data, this.curGroup);

			deleteKnowledgeBaseCategory(data.id)
				.then(res => {
					console.log(res);
					if (level === '1') {
						const index = this.groupList.findIndex(item => item.id === data.id);
						this.groupList.splice(index, 1);
						if (data.id === this.curGroup.id) {
							// 选择相邻节点或父节点 setCurrentKey
							this.$nextTick(() => {
								this.$refs.groupList.setCurrentKey(this.groupList[index - 1].id);
								this.curGroup = {...this.groupList[index - 1]};
							});
						}
					} else if (level === '2') {
						for (let i = 0; i < this.groupList.length; i++) {
							const item = this.groupList[i];
							if (item.id === parentId && item.children) {
								const index = item.children.findIndex(item => item.id === data.id);
								item.children.splice(index, 1);
								if (item.children.length <= 0) {
									item.children = null;
								}
								if (data.id === this.curGroup.id) {
									// 选择相邻节点或父节点 setCurrentKey
									if (item.children && index - 1 > 0 && item.children[index - 1]) {
										this.$nextTick(() => {
											this.$refs.groupList.setCurrentKey(item.children[index - 1].id);
											this.curGroup = {...item.children[index - 1]};
										});
									} else {
										this.$nextTick(() => {
											this.$refs.groupList.setCurrentKey(item.id);
											this.curGroup = {...item};
										});
									}
								}
								break;
							}
						}
					} else {
						this.groupList.forEach(item => {
							if (item.children) {
								item.children.forEach(subItem => {
									if (subItem.id === parentId && subItem.children) {
										const index = subItem.children.findIndex(item => item.id === data.id);
										subItem.children.splice(index, 1);
										if (subItem.children.length <= 0) {
											subItem.children = null;
										}
										if (data.id === this.curGroup.id) {
											// 选择相邻节点或父节点 setCurrentKey
											if (subItem.children && index - 1 > 0 && subItem.children[index - 1]) {
												this.$nextTick(() => {
													this.$refs.groupList.setCurrentKey(subItem.children[index - 1].id);
													this.curGroup = {...subItem.children[index - 1]};
												});
											} else {
												this.$nextTick(() => {
													this.$refs.groupList.setCurrentKey(subItem.id);
													this.curGroup = {...subItem};
												});
											}
										}
									}
								});
							}
						});
					}
					//
				})
				.catch(err => {
					console.log(err);
				});
		},
		// 处理分类删除
		handleGroupRemove(data) {
			console.log('handleGroupRemove', data);
			// 删除确认
			this.$confirm('删除后该分类下的所有内容都会删除, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.deleteKnowledgeBaseCategory(data);
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
		},
		// 处理新增分类
		handleGroupAdd(data) {
			console.log('handleGroupAdd', data);
			this.curGroup = {};
			this.parentGroupId = data.id;
			this.createGroupVisible = true;
		},
		// 处理批量分类编辑
		handleEditCatagory(data) {
			console.log(data);
			this.curMultipleSelection = data;
			this.editGroupVisible = true;
		},
		// 批量分类编辑
		handleEditCatagoryConfirm(data) {
			console.log(data);
			this.batchUpdateKnowledgeBaseCategory(data.group);
			this.editGroupVisible = false;
		},
		// 处理查询
		handleSearch(data) {
			this.curSearchName = data;
			this.queryMode = 'search';
			this.curGroup = {};
		},
		// 批量分类更新
		batchUpdateKnowledgeBaseCategory(catagory) {
			// {"categoryId":22,"knowledgeIds": [14,15,16,17]}
			const ids = this.curMultipleSelection.map(item => {
				return item.id;
			});
			const id = catagory[catagory.length - 1];
			batchUpdateKnowledgeBaseCategory({ categoryId: id, knowledgeIds: ids })
				.then(res => {
					console.log(res);
					this.$refs.QuestionList.getKnowledgeBaseList();
					this.$refs.QuestionList.clearSelection();
				})
				.catch(err => {
					console.log(err);
					this.$message.error('变更分类失败');
				});
		},
		async handleCreateQuestion(question) {
			console.log('handleCreateQuestion', question);
			this.queryMode = 'category';
			if (question.categoryId == 0) {
				// 未分类
				this.$nextTick(() => {
					this.$refs.groupList.setCurrentKey(question.categoryId);
					this.curGroup = {id: question.categoryId};
				});
				return;
			}
			try {
				const {data} = await getKnowledgeBaseCategoryParent(question.categoryId);
				const ids = extractIds(data.data);
				console.log('extractIds', ids);
				if (ids.length > 1) {
					this.$refs.groupList.addExpandedKeys(ids[ids.length - 2]);
				}
				// 展开父节点
				this.$nextTick(() => {
					this.$refs.groupList.setCurrentKey(question.categoryId);
					this.curGroup = {id: question.categoryId};
				});
			} catch (error) {
				console.log(error);
			}
		},
	}
};
</script>
<style scoped lang="less">
.knowledge-base-container {
	padding: 0 20px 20px 20px;
	box-sizing: border-box;
	height: 100%;
	width: 100%;
}
</style>
<style>
.knowledge-base-container .el-tabs {
	height: 100%;
}
.knowledge-base-container .el-tabs .el-tabs__content {
	height: calc(100% - 40px);
}
.knowledge-base-container .el-tabs .el-tabs__content .el-tab-pane {
	display: flex;
	height: 100%;
}
</style>
